#include "Camera.h"

#include "BaseObject.h"
#include "Tile.h"

#include "../wrappers/CSGD_EventSystem.h"

#include <cassert>

#define RIGHTSCROLLSTART 500.0f
#define LEFTSCROLLSTART 300.0f


CCamera* CCamera::s_Instance = nullptr;


CCamera* CCamera::GetInstance( void )
{
	if( s_Instance == nullptr )
		s_Instance = new CCamera;

	return s_Instance;
}


void CCamera::DeleteInstance( void )
{
	if( s_Instance != nullptr )
		delete s_Instance;
}


CCamera::CCamera(void)
{
	m_pPlayer = nullptr;
}


CCamera::~CCamera(void)
{
}


void CCamera::Initialize( CBaseObject* pPlayer, int nScreenWidth,
		int nScreenHeight,  float fStartingPos )
{
	assert( pPlayer != nullptr && "CCamera::Initialize - pPlayer null value" );
	m_pPlayer		= pPlayer;
	m_pPlayer->AddRef();

	m_nScreenHeight	= nScreenHeight;
	m_nScreenWidth  = nScreenWidth;
	m_fWorldPosition= fStartingPos;

}


void CCamera::Shutdown( void )
{
	if( m_pPlayer != nullptr )
		m_pPlayer->Release();
}


float CCamera::UpdateCamera( void )
{
	assert( m_pPlayer != nullptr && "CCamera::UpdateCamera - m_pPlayer null value" );
	float dPosition = 0.0f;
	if( m_pPlayer->GetRelativePosition().fX > RIGHTSCROLLSTART )
		dPosition = (m_pPlayer->GetRelativePosition().fX - RIGHTSCROLLSTART);
	else if( m_pPlayer->GetRelativePosition().fX < LEFTSCROLLSTART && m_fWorldPosition > 0.0f )
		dPosition = -(LEFTSCROLLSTART - m_pPlayer->GetRelativePosition().fX);

	m_fWorldPosition += dPosition;
	return dPosition;
}


bool CCamera::OnCamera( float fX )
{
	if( fX > m_fWorldPosition && 
		fX < m_fWorldPosition + (float)m_nScreenWidth )
		return true;
	else
		return false;
}


bool CCamera::OnCamera( CBaseObject* pOther )
{
	vector< CBaseObject* >::iterator objIter = m_VisibleObjects.begin();
	for( ; objIter != m_VisibleObjects.end(); ++objIter )
	{
		if( (*objIter) == pOther )
			return true;
	}

	return false;
}


void CCamera::UpdateCameraPosition( CBaseObject* pObject )
{
	pObject->SetRelativeXPosition( pObject->GetPosition().fX - m_fWorldPosition );

	if( OnCamera(pObject) == false )
	{
		if( OnCamera( (float)pObject->GetRect().right ) ||
			OnCamera( (float)pObject->GetRect().left ) )
		{
			m_VisibleObjects.push_back( pObject );
		}
	}
}
